#include "caskmovecontrol.h"

CaskMoveControl::CaskMoveControl(QWidget *parent)
    : QWidget{parent}
{

}

CaskMoveControl::CaskMoveControl(const QString &name, const QJsonObject &functionDetails,const QString deviceName,  QWidget *parent)
    : QWidget{parent}
{

    mDeviceID = deviceName;
    /* ───────────── 0. 根布局 ───────────── */
    auto *layout = new QVBoxLayout(this);
    layout->setContentsMargins(0, 0, 0, 0);  // 边距留给 container 处理
    layout->setSpacing(0);
    layout->setAlignment(Qt::AlignTop);  // 设置垂直方向的对齐方式为顶部对齐

    /* ───────────── 1. 外层容器 — 带圆角边框 ───────────── */
    QFrame *container = new QFrame(this);
    container->setObjectName("outerFrame");
    container->setFrameShape(QFrame::NoFrame);

    // QSS: 圆角边框 + 背景
    container->setStyleSheet(R"(
        QFrame#outerFrame {
            background-color: #11213A;
            border: 1px solid #3E4C61;
            border-radius: 8px;
        }
    )");

    auto *containerLay = new QVBoxLayout(container);
    containerLay->setContentsMargins(12, 12, 12, 12);
    containerLay->setSpacing(12);

    /* ───────────── 2. 头部 widget ───────────── */
    QWidget *headerWidget = new QWidget(container);
    QHBoxLayout *headerLay = new QHBoxLayout(headerWidget);
    headerLay->setContentsMargins(0, 0, 0, 0);
    headerLay->setSpacing(6);

    QLabel *iconLbl  = new QLabel(headerWidget);
    // iconLbl->setPixmap(QIcon(":/img/connect.png").pixmap(18, 18));
    if (name.contains("MoveJoint")) {
        iconLbl->setPixmap(QIcon(":/img/connect.png").pixmap(18, 18));
    } else if (name.contains("MoveTool")) {
        iconLbl->setPixmap(QIcon(":/img/arrow4.png").pixmap(18, 18));
    } else if (name.contains("Tcp Control")) {
        iconLbl->setPixmap(QIcon(":/img/sliders.png").pixmap(18, 18));
    } else {
        iconLbl->setPixmap(QIcon(":/img/connect.png").pixmap(18, 18)); // 默认
    }


    QLabel *titleLbl = new QLabel(name, headerWidget);
    titleLbl->setStyleSheet("color:#F0B532; font-weight:bold; font-size:17px;");

    headerLay->addWidget(iconLbl);
    headerLay->addWidget(titleLbl);
    headerLay->addStretch();

    containerLay->addWidget(headerWidget);

    /* ───────────── 3. 主 groupBox ───────────── */
    QGroupBox *groupBox = new QGroupBox(name, container);
    groupBox->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);

    // —— 隐藏白色边框 & 标题 ——
    groupBox->setTitle("");
    groupBox->setFlat(true);
    groupBox->setStyleSheet(R"(
        QGroupBox {
            border: none;
            margin-top: 0px;
        }
    )");

    createCaskMoveControl(groupBox, functionDetails);
    containerLay->addWidget(groupBox);

    /* ───────────── 4. 把 container 挂到根布局 ───────────── */
    layout->addWidget(container);

}

CaskMoveControl::~CaskMoveControl()
{
    // currentDevice = mDeviceID;
    // DeviceManager::instance().removeNode(mDeviceID);
    qDebug() << "CaskMoveControl in xiGOU";
}

// void CaskMoveControl::createCaskMoveControl(QGroupBox *groupBox, const QJsonObject &functionDetails)
// {
//     QVBoxLayout *mainLayout = new QVBoxLayout(groupBox);
//     qDebug() << "functionDetails:" << functionDetails << Qt::endl;

//     mainLayout->setAlignment(Qt::AlignTop);  // 设置垂直方向的对齐方式为顶部对齐
//     for (auto it = functionDetails.begin(); it != functionDetails.end(); ++it)
//     {
//         QString key = it.key();  // "moveHinge" 或 "moveShuttle"
//         QJsonObject controlDetails = it.value().toObject();
//         if(key == "lock")
//         {
//             // continue;
//             // 创建弹簧控件
//             QSpacerItem *spacer1 = new QSpacerItem(20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
//             QSpacerItem *spacer2 = new QSpacerItem(20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
//             QSpacerItem *spacer3 = new QSpacerItem(20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
//             QSpacerItem *spacer4 = new QSpacerItem(20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
//             QSpacerItem *spacer5 = new QSpacerItem(20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);

//             QWidget *widget = new QWidget(groupBox);
//             QHBoxLayout *layout = new QHBoxLayout(widget);
//             widget->setLayout(layout);

//             // 设置 QLabel
//             QLabel *label = new QLabel(controlDetails["label"].toString() + " :", widget);
//             label->setFixedWidth(90);
//             label->setAlignment(Qt::AlignCenter);
//             layout->addItem(spacer1);  // 左侧弹簧
//             layout->addWidget(label);  // 标签

//             // 设置 QPushButton
//             QPushButton *button = new QPushButton(controlDetails["pushbutton"].toString(), widget);
//             label->setFixedWidth(100);
//             button->setObjectName("btn_" + key);
//             layout->addItem(spacer2);
//             layout->addWidget(button);
//             layout->addItem(spacer3);
//             // 添加两个空的 QWidget 来占位
//             QWidget *emptyWidget1 = new QWidget(widget);
//             emptyWidget1->setFixedWidth(100);  // 设置一个固定宽度的空控件
//             QWidget *emptyWidget2 = new QWidget(widget);
//             emptyWidget2->setFixedWidth(100);  // 设置一个固定宽度的空控件
//             layout->addWidget(emptyWidget1);  // 添加第一个占位控件
//             layout->addItem(spacer4);
//             layout->addWidget(emptyWidget2);  // 添加第二个占位控件
//             layout->addItem(spacer5);
//             // 连接按钮点击信号到同一个槽函数
//             connect(button, &QPushButton::clicked, this, &CaskMoveControl::onButtonClicked);

//             mainLayout->addWidget(widget);
//             continue;
//         }
//         // 创建弹簧控件
//         QSpacerItem *spacer1 = new QSpacerItem(20, 40, QSizePolicy::Expanding, QSizePolicy::Minimum);
//         QSpacerItem *spacer3 = new QSpacerItem(20, 40, QSizePolicy::Expanding, QSizePolicy::Minimum);
//         QSpacerItem *spacer4 = new QSpacerItem(20, 40, QSizePolicy::Expanding, QSizePolicy::Minimum);

//         QWidget *widget = new QWidget(groupBox);
//         QHBoxLayout *layout = new QHBoxLayout(widget);
//         widget->setLayout(layout);

//         // 设置 QLabel
//         QLabel *label = new QLabel(controlDetails["label"].toString() + " :", widget);
//         label->setFixedWidth(90);
//         label->setAlignment(Qt::AlignCenter);
//         QFont labelFont = label->font();
//         label->setFont(labelFont);
//         layout->addItem(spacer3);  // 左侧弹簧
//         layout->addWidget(label);  // 标签

//         // 设置 QLineEdit
//         QLineEdit *lineEdit = new QLineEdit(widget);
//         lineEdit->setObjectName(controlDetails["lineedit"].toString());
//         QFont lineEditFont = lineEdit->font();
//         lineEdit->setFont(lineEditFont);
//         lineEdit->setFixedWidth(120);  // 设置较大宽度
//         layout->addItem(spacer1);  // 输入框左边的弹簧
//         layout->addWidget(lineEdit);  // 输入框

//         // 存储 QLineEdit 到 Map 中，方便后续访问
//         lineEditMap.insert(key, lineEdit);

//         // 创建并添加 QPushButton
//         QJsonArray pushButtons = controlDetails["pushbutton"].toArray();
//         for (const auto& buttonName : pushButtons) {
//             QPushButton *button = new QPushButton(buttonName.toString(), widget);
//             button->setObjectName("btn_" + buttonName.toString());  // 设置按钮的 objectName
//             QFont buttonFont = button->font();
//             button->setFont(buttonFont);
//             button->setFixedWidth(90);  // 设置按钮宽度为 100，根据需要调整
//             QSpacerItem *spacer2 = new QSpacerItem(20, 40, QSizePolicy::Expanding, QSizePolicy::Minimum);
//             layout->addItem(spacer2);  // 按钮与输入框之间的间隔
//             layout->addWidget(button);  // 按钮

//             // 连接按钮点击信号到同一个槽函数
//             connect(button, &QPushButton::clicked, this, &CaskMoveControl::onButtonClicked);
//         }

//         layout->addItem(spacer4);  // 右侧弹簧
//         mainLayout->addWidget(widget);  // 将控件添加到主布局
//     }

//     groupBox->setLayout(mainLayout);
// }

void CaskMoveControl::createCaskMoveControl(QGroupBox *groupBox, const QJsonObject &functionDetails)
{
    QVBoxLayout *mainLayout = new QVBoxLayout(groupBox);
    // qDebug() << "functionDetails:" << functionDetails << Qt::endl;

    mainLayout->setAlignment(Qt::AlignTop);  // 设置垂直方向的对齐方式为顶部对齐
    mainLayout->setSpacing(16);

    qDebug() << "initMsg size:" << initMsg.size();

    for (auto it = functionDetails.begin(); it != functionDetails.end(); ++it)
    {
        QString key = it.key();  // "moveHinge" 或 "moveShuttle"
        if(key == "reset") continue;
        QJsonObject controlDetails = it.value().toObject();
        // 如果是 flag1, 就根据这个键的详细信息动态添加控件
        if (controlDetails.contains("flag1"))
        {
            QJsonObject flagDetails = controlDetails["flag1"].toObject();
            Flag1Control *flag1Widget = new Flag1Control(flagDetails, mDeviceID,groupBox);
            mainLayout->addWidget(flag1Widget); // 将 flag1 控件添加到主布局中

            //通信设置
            //8.01
            currentDevice = mDeviceID;
            DeviceManager::instance().nodeFor(mDeviceID);
            auto node = DeviceManager::instance().nodeFor(currentDevice);
            flag1Widget->attachToNode(node);

            continue;
        }
        // 如果是 flag2, 就根据这个键的详细信息动态添加控件
        if (controlDetails.contains("flag2"))
        {
            QJsonObject flagDetails = controlDetails["flag2"].toObject();
            Flag2Control *flag2Widget = new Flag2Control(flagDetails, mDeviceID,groupBox);
            mainLayout->addWidget(flag2Widget); // 将 flag2 控件添加到主布局中

            //通信设置
            //8.01
            currentDevice = mDeviceID;
            DeviceManager::instance().nodeFor(mDeviceID);
            auto node = DeviceManager::instance().nodeFor(currentDevice);
            flag2Widget->attachToNode(node);

            continue;
        }
        if(controlDetails.contains("flag3"))
        {
            QJsonObject flagDetails = controlDetails["flag3"].toObject();
            Flag3Control *flag3Widget = new Flag3Control(flagDetails,mDeviceID ,groupBox);
            flag3Controls.append(flag3Widget);  // 保存指针

            // 连接 flag3 控件的角度变化信号到槽函数
            connect(flag3Widget, &Flag3Control::angleChanged,
                    this, &CaskMoveControl::onFlag3AngleChanged);

            // ▽—— 2) 用 QFrame 包一层，给它取个名字
            QFrame *rowFrame = new QFrame;
            rowFrame->setObjectName("jointRowFrame");
            rowFrame->setFrameShape(QFrame::NoFrame);

            // ▽—— 3) 把真正的行内控件放到这个 frame 的布局里
            QHBoxLayout *rowLay = new QHBoxLayout(rowFrame);
            rowLay->setContentsMargins(0, 0, 0, 0);
            rowLay->addWidget(flag3Widget);

            // ▽—— 4) 给 frame 下样式：圆角 + 边框 + 内边距 + 下边距
            rowFrame->setStyleSheet(R"(
                QFrame#jointRowFrame {
                    background: rgba(255,255,255,0.05);
                    border: 1px solid #334155;
                    border-radius: 8px;
                    padding: 10px;
                    margin-bottom: 10px;
                }
            )");

            // ▽—— 5) 最后把这个 frame 加到主布局
            mainLayout->addWidget(rowFrame);

            //通信设置
            // currentDevice = mDeviceID;
            // DeviceManager::instance().nodeFor(mDeviceID);
            // auto node = DeviceManager::instance().nodeFor(currentDevice);
            // flag3Widget->attachToNode(node);

            // continue;
            // qDebug() << "controlDetails:" << controlDetails << Qt::endl;

        }
        // 新增：flag5 处理逻辑（ToolPushButton）
        if (controlDetails.contains("flag5"))
        {
            QJsonObject flag5Details = controlDetails["flag5"].toObject();

            ToolPushButton* toolPushBtnWidget = new ToolPushButton(groupBox);
            toolPushBtnWidget->setCommands(flag5Details);
            // 设置最小高度
            toolPushBtnWidget->setMinimumHeight(200);  // 设置最小高度为 200 像素

            connect(toolPushBtnWidget, &ToolPushButton::commandTriggered, this, [this](const QString &cmd){
                //qDebug() << "ToolPushButton command triggered:" << cmd;
                // 这里写你需要执行命令的逻辑，比如发信号、调用接口等

                //发布消息
                pubMsg(cmd);
            });

            mainLayout->addWidget(toolPushBtnWidget);
            continue;
        }
        if (controlDetails.contains("flag_lab_cbx"))
        {
            QJsonObject flagDetails = controlDetails["flag_lab_cbx"].toObject();

            // 创建 flag2Widget
            Flag_Lab_Cbx *flag2Widget = new Flag_Lab_Cbx(flagDetails, groupBox);

            // 创建水平布局
            QHBoxLayout *hLayout = new QHBoxLayout();

            // 创建左右弹簧
            // QSpacerItem *leftSpacer = new QSpacerItem(20, 0, QSizePolicy::Expanding, QSizePolicy::Minimum);
            // QSpacerItem *rightSpacer = new QSpacerItem(20, 0, QSizePolicy::Expanding, QSizePolicy::Minimum);

            // 添加弹簧和控件到布局
            // hLayout->addItem(leftSpacer);  // 左侧弹簧
            hLayout->addWidget(flag2Widget);  // 中间的 flag2 控件
            // hLayout->addItem(rightSpacer);  // 右侧弹簧

            // 将 hLayout 添加到主布局中
            mainLayout->addLayout(hLayout);  // 使用 addLayout 而不是 addWidget

            continue;
        }

        if (controlDetails.contains("flag_ptn_ptn_ptn"))
        {
            QJsonObject flagDetails = controlDetails["flag_ptn_ptn_ptn"].toObject();
            qDebug() << "flagDetails:" << flagDetails << Qt::endl;

            // 创建 Flag_Ptn_Ptn_Ptn 控件
            Flag_Ptn_Ptn_Ptn *flag2Widget = new Flag_Ptn_Ptn_Ptn(flagDetails, groupBox);

            // 创建水平布局
            QHBoxLayout *hLayout = new QHBoxLayout();

            // 创建左右弹簧
            // QSpacerItem *leftSpacer = new QSpacerItem(20, 0, QSizePolicy::Expanding, QSizePolicy::Minimum);
            // QSpacerItem *rightSpacer = new QSpacerItem(20, 0, QSizePolicy::Expanding, QSizePolicy::Minimum);

            // 添加弹簧和控件到布局
            // hLayout->addItem(leftSpacer);  // 左侧弹簧
            hLayout->addWidget(flag2Widget);  // 中间的 flag2 控件
            // hLayout->addItem(rightSpacer);  // 右侧弹簧

            // 将 hLayout 添加到主布局中
            mainLayout->addLayout(hLayout);  // 使用 addLayout 而不是 addWidget

            continue;
        }

        if (controlDetails.contains("flag_lab_le_lab"))
        {
            QJsonObject flagDetails = controlDetails["flag_lab_le_lab"].toObject();
            qDebug() << "flagDetails:" << flagDetails << Qt::endl;

            // 创建 Flag_Lab_Le_Lab 控件
            Flag_Lab_Le_Lab *flag2Widget = new Flag_Lab_Le_Lab(flagDetails, groupBox);

            // 创建水平布局
            QHBoxLayout *hLayout = new QHBoxLayout();

            // 创建左右弹簧
            // QSpacerItem *leftSpacer = new QSpacerItem(20, 0, QSizePolicy::Expanding, QSizePolicy::Minimum);
            // QSpacerItem *rightSpacer = new QSpacerItem(20, 0, QSizePolicy::Expanding, QSizePolicy::Minimum);

            // 添加弹簧和控件到布局
            // hLayout->addItem(leftSpacer);  // 左侧弹簧
            hLayout->addWidget(flag2Widget);  // 中间的 flag2 控件
            // hLayout->addItem(rightSpacer);  // 右侧弹簧

            // 将 hLayout 添加到主布局中
            mainLayout->addLayout(hLayout);  // 使用 addLayout 而不是 addWidget

            continue;
        }

    }
    if (functionDetails.contains("reset"))
    {
        getFlag3Angles();

        QString resetCommand = functionDetails["reset"]
                                   .toObject()["flag4"]
                                   .toObject()["pushbutton1"]
                                   .toObject()["Commands"]
                                   .toString();

        QPushButton *resetAllBtn = new QPushButton("重置所有关节角度", groupBox);
        resetAllBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);

        // 设置图标
        QIcon icon(":/img/reset.png");  // 替换为你实际图标路径
        resetAllBtn->setIcon(icon);
        resetAllBtn->setIconSize(QSize(18, 18));  // 根据图标大小调整
        resetAllBtn->setStyleSheet(R"(
            QPushButton {
                background: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0,
                                            stop:0 #fbc02d, stop:1 #e65100);
                color: #333333;
                border: none;
                padding: 5px 20px;
                border-radius: 8px;
                font-size: 18px;              /* 字体更大 */
                font-weight: 700;            /* 更加粗体 */
                font-family: 'Microsoft YaHei';
                qproperty-iconSize: 16px;
                text-align: center;
            }
            QPushButton:hover {
                background: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0,
                                            stop:0 #e65100, stop:1 #bf360c);
            }
        )");
        resetAllBtn->setLayoutDirection(Qt::LeftToRight);  // 图标在文字左边
        resetAllBtn->setContentsMargins(0, 0, 0, 0);
        resetAllBtn->setMinimumHeight(40);  // 控制高度，与图中类似
        mainLayout->addWidget(resetAllBtn);

        connect(resetAllBtn, &QPushButton::clicked, this, [this, resetCommand]() {

            //EmptyWorkingSet(GetCurrentProcess()); // 请求 OS 清空该进程的工作集

            for (Flag3Control* flag3 : flag3Controls) {
                if (flag3)
                    flag3->reset();
            }
            qDebug() << "Executing reset command 123:" << resetCommand;
            // 可在此处发信号、调用接口等
            QString pubContent;
            pubContent = resetCommand;


            for (auto it = initMsg.constBegin(); it != initMsg.constEnd(); ++it) {
                if (pubContent.contains(it.key())) {
                    pubContent.replace("<value>", it.value());

                    break;  // 找到第一个匹配的 key 就替换并退出
                }

            }
            pubMsg(pubContent);//发布控制消息，初始化重置

            for (Flag3Control* flag3 : flag3Controls)
            {
                if (flag3)
                {
                    QString name = flag3->getJointName();        // 获取名称//setDefaultPosition
                    double initValue = initMsg.value(name).toDouble();
                    initValue = (initValue+0.005)*100;
                    int initValueInt = static_cast<int>(initValue);
                    flag3->setDefaultPosition(initValueInt);

                    // QString angle = flag3->getAngleDisplay()->text();  // 获取当前角度文本
                    // flag3Angles.push_back({ name, angle });
                    // qDebug() << "Flag3Control: " << name << ", Angle: " << angle;
                }
            }
        });


    }


    groupBox->setLayout(mainLayout);
}

void CaskMoveControl::updateFlag3ControlSlot(const QJsonObject &jsonData)
{
    for (auto it = jsonData.begin(); it != jsonData.end(); ++it) {
        QString jointName = it.key();  // e.g., "joint_1"
        QJsonObject jointData = it.value().toObject();
        int minValue = jointData["min"].toInt();
        int maxValue = jointData["max"].toInt();
        int defaultValue = jointData["default"].toInt();

        for (Flag3Control* flag3 : flag3Controls) {
            if (flag3 && flag3->getJointName() == jointName) {
                flag3->setRange(minValue, maxValue);                     // ✅ 设置 min/max
                flag3->setDefaultPosition(defaultValue * 100);           // ✅ 设置默认值（单位：整型）
                qDebug() << "Updated flag3:" << jointName
                         << ", min:" << minValue
                         << ", max:" << maxValue
                         << ", default:" << defaultValue;
                break;
            }
        }
    }
}

void CaskMoveControl::getFlag3Angles()
{
    for (Flag3Control* flag3 : flag3Controls)
    {
        if (flag3)
        {
            QString name = flag3->getJointName();        // 获取名称
            QString angle = flag3->getAngleDisplay()->text();  // 获取当前角度文本
            flag3Angles.push_back({ name, angle });
            qDebug() << "Flag3Control: " << name << ", Angle: " << angle;
        }
    }
}

void CaskMoveControl::onFlag3AngleChanged(const QString &jointName, double angle,QString command)
{
    qDebug() << "Flag3Control " << jointName << " angle changed to: " << angle << command;

    // 这里可以维护一个数据结构，实时记录所有关节角度，例如：
    bool found = false;
    for (auto &pair : flag3Angles) {
        if (pair.first == jointName) {
            pair.second = QString::number(angle);
            found = true;
            break;
        }
    }

    if (!found) {
        flag3Angles.push_back({jointName, QString::number(angle)});
    }

    // 你也可以在这里写其他联动逻辑
    command.replace("<value>",QString::number(angle));
    pubMsg(command);
}

void CaskMoveControl::pubMsg(QString content)
{
    if(m_node)
    {
        QString id = mDeviceID;
        //QString id = "ORS_Cask";
        m_node->publishCmd(id,content);
    }
}


void CaskMoveControl::attachToNode(QSharedPointer<DeviceNode> node)
{
    if (m_node) {
        disconnect(m_node.data(), &DeviceNode::cmdReceived,
                   this, &CaskMoveControl::onDataReceived);
        // disconnect(m_node.data(), &DeviceNode::eventReceived,
        //            this, &CaskMoveControl::onEventReceived);
    }
    m_node = node;
    if (m_node) {
        connect(m_node.data(), &DeviceNode::cmdReceived,
                this, &CaskMoveControl::onDataReceived);
        // connect(m_node.data(), &DeviceNode::eventReceived,
        //         this, &CaskMoveControl::onEventReceived);
    }
}

void CaskMoveControl::onDataReceived(const QString &content)
{
    initCount = initCount > 10 ? 10 : (initCount+1);

    if(initCount<4)
        ctrlInitMsg(content);
}

void CaskMoveControl::ctrlInitMsg(const QString& content)
{
    QJsonDocument doc = QJsonDocument::fromJson(content.toUtf8());

    if (doc.isObject()) {
        QJsonObject obj = doc.object();

        QJsonObject::const_iterator iter = obj.constBegin();
        QString key;
        QJsonValue value;
        QString valueF;

        while (iter != obj.constEnd()) {
            key = iter.key();
            value = iter.value();
            valueF = " ";

            //  如果是数组类型
            if (value.isArray()) {
                QJsonArray jsonArray = value.toArray();
                QStringList valueList;

                int i = 1;
                for (const auto &element : jsonArray) {
                    QString valStr = QString::number(element.toDouble());
                    valueList << valStr;

                    // 把每个数组元素按 key1、key2 形式存入
                    QString nameX = key + QString::number(i);
                    initMsg[nameX] = valStr;
                    i++;
                }

                //将数组整体用 "(a,b,c)" 形式存入 initMsg[key]
                valueF = "(" + valueList.join(",") + ")";
                initMsg[key] = valueF;

                ++iter;
                continue;
            }

            // 处理普通类型：double, bool, string
            if (value.isDouble()) {
                valueF = QString::number(value.toDouble());
            } else if (value.isBool()) {
                valueF = value.toBool() ? "TRUE" : "FALSE";
            } else if (value.isString()) {
                valueF = value.toString();
            } else {
                qDebug() << key << ": unknown type";
            }

            initMsg[key] = valueF;
            ++iter;
        }
    } else {
        qDebug() << "Failed to parse JSON." << Qt::endl;
    }

    for (Flag3Control* flag3 : flag3Controls)
    {
        if (flag3)
        {
            QString name = flag3->getJointName();        // 获取名称//setDefaultPosition
            double initValue = initMsg.value(name).toDouble();
            initValue = (initValue+0.005)*100;
            int initValueInt = static_cast<int>(initValue);
            flag3->setDefaultPosition(initValueInt);
            //qDebug() << "Flag3Control123333: " <<initValue<<Qt::endl;
            // QString angle = flag3->getAngleDisplay()->text();  // 获取当前角度文本
            // flag3Angles.push_back({ name, angle });
            //qDebug() << "Flag3Control123333: " << name << ", Angle: " << angle;
        }
    }
}


